import { createRouter, createWebHashHistory } from 'vue-router';
import { checkIsLogin } from '@/utils/checkIsLogin';

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            name: 'home',
            component: () => import('../views/Main.vue'),
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/Login.vue'),
        },
        {
            path: '/todo2',
            name: 'todo2',
            component: () => import('../views/Main2.vue'),
        },
        {
            path: '/test',
            name: 'test1',
            redirect: {name: 'test2'},
            component: () => import('../views/Test.vue'),
            children: [
                {
                    path: 'test2',
                    name: 'test2',
                    component: () => import('../views/Test2.vue'),
                },
                {
                    path: 'test3',
                    name: 'test3',
                    component: () => import('../views/Test3.vue'),
                },
            ],
        },
    ],
});

router.beforeEach(async (to, from, next) => {
    if (to.name === 'login') {
        next();
    } else {
        try {
            await checkIsLogin();
            next();
        } catch (e) {
            router.push({name: 'login'});
            next(false);
        }
    }
});
export default router;
